# coding:utf-8
# Project:pyinterface
# author:wj
# time:2022/12/30 17:47
# Email:1305137785@qq.com
import pymysql
from conf.settings import mysql_info
import traceback

class MysqlHandle:
    def __init__(self, dbname):
        # 创建数据库连接
        self.db = pymysql.connect(
            host=mysql_info['host'],
            user=mysql_info['user'],
            passwd=mysql_info['password'],
            port=mysql_info['port'],
            autocommit=True,
            database=dbname,
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor
        )
        # 创建数据库游标
        self.cur = self.db.cursor()

    def get_data(self, sql):
        # 数据库异常操作
        try:
            self.cur.execute(sql)
            result = self.cur.fetchall()
            print(result, type(result))
            value_list = [];
            # result 是个列表，列表里包的是字典，经过第一层的for循环后得到的是字典
            for var in result:
                # 又经过一层for循环后，取出字符串，然后将所有的值拼接到一个列表中
                for value in var.values():
                    value_list.append(value)
        except Exception as e:
            print(e, traceback.print_exc())
            self.db.rollback()
        finally:
            self.close_db();
            return value_list;

    #     执行
    def excute_sql(self, sql, list_sql):
        self.cur.execute(sql, list_sql)

    #    关闭数据库
    def close_db(self):
        self.cur.close();
        self.db.close()


if __name__ == '__main__':
    MysqlHandle(dbname="facilitator").get_data(sql="select count(*) from account where company_id = 72011920")
